<?php

    class PostController extends WebController
    {

        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                    'actions'=>array('index','view','search','admin','delete', 'create','update', 'offer'),
                    'users'=>array('*'),
                ),
                //			array('allow', // allow authenticated user to perform 'create' and 'update' actions
                //				'actions'=>array(),
                //				'users'=>array('@'),
                //			),
                //			array('allow', // allow admin user to perform 'admin' and 'delete' actions
                //				'actions'=>array('admin','delete', 'create','update'),
                //                'expression'    =>  '$user->user->isMod', 
                //			),
                //			array('deny',  // deny all users
                //				'users'=>array('*'),
                //			),
            );
        }

        public function actionOffer($alias)
        {
            $postOffer = PostOffer::model()->findByAttributes(array('alias' => $alias));
            if($postOffer->url) $this->redirect($postOffer->url);
            $this->redirect('/');
        }
        

        public function actionView($alias = null, $id = null)
        {   
            $alias_id = $id ? $id : $alias;
            $post = $this->loadModel($alias_id);

            
            if(!$alias) $this->noIndexFollow = true;
            $this->siteNameIsH1 = false;

            $post->view += 1;
            $post->update();

            $hasVideo = $post->detectVideo();

            $this->pageDesc = $post->desc;
            $this->pageTitle = $post->title;
            $this->ogImage = $post->imageUrlSmall;
            $this->ogUrl = $post->url;
            
            $this->render('view',array(
                'post'=>$post,
                'hasVideo'=>$hasVideo,
            ));
        }


        public function actionIndex($cat_alias = null, $lang='vi')
        {   
            $cat = PostCat::model()->findByAttributes(array('alias' => $cat_alias));
            
            $this->siteNameIsH1 = false;
            $currentTime = MyDateTime::getCurrentTime();
            
            $criteria=new CDbCriteria;
            if($cat) $criteria->addCondition("t.cat_id = {$cat->id}");
            $criteria->addCondition("t.`status` = 'ENABLE'");
            $criteria->addCondition("t.`created` < '{$currentTime}'");
            $criteria->order = "t.created DESC";
            
            if($cat){
                $this->pageTitle = $cat->name .' - '. $this->siteName;
                $this->pageDesc = $cat->desc;     
            }else{
                $this->pageTitle = 'Bản tin Giặt Là Vui - '. $this->siteName;
                $this->pageDesc = 'Cập nhật những tin tức, thủ thuật, chia sẻ phương pháp giặt là của Giặt Là Vui.';   
            }
            
            $this->menu_selected = $cat ? $cat->alias : 'post';
            
            $dataProvider = new CActiveDataProvider('Post', array(
                'criteria'=>$criteria,
                'pagination' => array(
                    'pageSize' => 10,
                    'pageVar' => 'page',
                ),
            ));

            $pagination = new CPagination($dataProvider->totalItemCount);
            $pagination->setPageSize($dataProvider->pagination->pageSize);
            $pagination->pageVar = 'page';

            $this->render('index', compact('cat', 'dataProvider', 'pagination'));
        }

        public function actionSearch($term = null){
            $q = Yii::app()->request->getPost('q');
            if($q)      $this->redirect(array('/web/post/search', 'term' => $q));
            if(!$term)  $this->redirect($this->baseUrl);
            
            
            $term = preg_replace('{[-+\s]+}', ' ', $term);
            $this->keyword_search = $term_title = mb_convert_case($term, MB_CASE_TITLE, "UTF-8");

            Yii::import('application.vendors.*');
            require_once('Zend/Search/Lucene.php');
            $indexPath = "application.runtime.search.".Yii::app()->params->site['nameShort'].".post";


            Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive());
            Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
            Zend_Search_Lucene::setResultSetLimit(200);

            $index = new Zend_Search_Lucene(Yii::getPathOfAlias($indexPath));


            $title = "{$term_title}";
            
            $results = $index->find($term 
//                ,'title', SORT_STRING, SORT_DESC
//                ,'p_title', SORT_STRING, SORT_DESC   
//                ,'desc', SORT_STRING, SORT_DESC
//                ,'content', SORT_STRING, SORT_DESC
//                ,'p_content', SORT_STRING, SORT_DESC  
            );

            $this->pageTitle = "{$title} - ". $this->siteName;
                 
            $dataProvider = new CArrayDataProvider($results, array(
                'pagination'=>array(
                    'pageSize'=>10,
                    'pageVar' => 'page',
                ),
            ));
            $pagination = new CPagination($dataProvider->totalItemCount);
            $pagination->setPageSize($dataProvider->pagination->pageSize);
            $pagination->pageVar = 'page';
                      
            $this->render('search', compact('dataProvider', 'pagination', 'term_title'));
        }
        
        
        /**
        * put your comment there...
        * 
        * @param mixed $alias
        * @return Post
        */
        public function loadModel($alias_id)
        {
            $params = is_numeric($alias_id) ? array('id' => $alias_id) : array('alias' => $alias_id);
            
            $model = Post::model()->with(array(
                'cat', 'manager'
            ))->findByAttributes($params);
            
            if($model===null || $model->status != 'ENABLE'){
                throw new CHttpException(404,'The requested page does not exist.');
            }

            return $model;
        }
        

    }
